package top.chatgqt.SmartChargeStation.demo.netty.handlers;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;
import top.chatgqt.SmartChargeStation.demo.netty.utils.ConnectUtil;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ImoocClientDisconnHandler extends ChannelInboundHandlerAdapter {

    private ConnectUtil util = new ConnectUtil();

    // Channel连接成功触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    // Channel断开连接触发
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        // 客户端进行重新连接机制
        log.info(">>>> Netty 客户端和服务端断开连接");
        // 如果连接不上，单独启动一条线程重新连接
        final EventLoop loop = ctx.channel().eventLoop();
        loop.schedule(new Runnable() {
            @Override
            public void run() {
                util.connect("127.0.0.1", 1919);
            }
        }, 10, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }

    // 收到消息触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }
}
